/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.view.jsp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TryCatchFinally;
import org.stripesbook.rayures.exception.RequiredTagAttributeException;
import org.stripesbook.rayures.view.ViewContext;
import org.stripesbook.rayures.view.ViewObject;

public class JspTagWrapper<T extends Tag, V extends JspTagWrapper<?, ?>> extends ViewObject<V> {

  private T tag;
  private IterationTag iterationTag;
  private BodyTag bodyTag;
  private PageContext pageContext;
  private boolean tagParent;

  public JspTagWrapper(T tag) {
    this.tag = tag;

    if (tag instanceof IterationTag) {
      this.iterationTag = (IterationTag) tag;
    }
    if (tag instanceof BodyTag) {
      this.bodyTag = (BodyTag) tag;
    }
  }

  public T getTag() {
    return tag;
  }

  @SuppressWarnings("unchecked")
  public V add(Tag... childTags) {
    for (Tag childTag : childTags) {
      add(new JspTagWrapper(childTag));
    }
    return getThis();
  }

  @Override
  public void setParent(ViewObject<?> parent) {
    super.setParent(parent);

    if (parent instanceof JspTagWrapper<?, ?>) {
      getTag().setParent(((JspTagWrapper<?, ?>) parent).getTag());
      tagParent = true;
    }
  }

  @Override
  public String toString() {
    validate();

    if (!tagParent) {
      // Search ancestors for JspTagWrapper parent
      ViewObject<?> parent = getParent();
      while (parent != null && !(parent instanceof JspTagWrapper<?, ?>)) {
        parent = parent.getParent();
      }
      if (parent != null) {
        getTag().setParent(((JspTagWrapper<?, ?>) parent).getTag());
      }
    }

    String result = null;
    TryCatchFinally tcf = null;
    if (TryCatchFinally.class.isAssignableFrom(tag.getClass())) {
      tcf = (TryCatchFinally) tag;
    }
    try {
      ViewContext viewContext = getViewContext();
      if (viewContext == null) {
        throw new NullPointerException("The view context is null. Most likely, you created a tag "
          + "instance directly with 'new'. Please use the tag() method instead.");
      }
      HttpServletRequest request = viewContext.getRequest();
      HttpServletResponse response = viewContext.getResponse();
      pageContext = createPageContext(request, response);
      tag.setPageContext(pageContext);
      process(tag);
      result = pageContext.getOut().toString();
    }
    catch (RequiredTagAttributeException exc) {
      throw exc;
    }
    catch (Throwable t) {
      if (tcf != null) {
        try {
          tcf.doCatch(t);
        }
        catch (Throwable t2) {
          throw new RuntimeException("Exception in doCatch() for exception:", t);
        }
      }
      else {
        throw new RuntimeException("Exception in JSP tag", t);
      }
    }
    finally {
      if (tcf != null) {
        tcf.doFinally();
      }
    }
    return result;
  }

  protected PageContext createPageContext(HttpServletRequest request, HttpServletResponse response) {
    return new JspPageContext(request, response);
  }

  protected void process(Tag tag) throws Exception {
    int result = tag.doStartTag();
    process(tag, result);
  }

  protected void process(Tag tag, int result) throws Exception {
    if (result == Tag.SKIP_BODY) {
      doEndTag(tag);
    }
    else if (result == Tag.EVAL_BODY_INCLUDE
          || result == BodyTag.EVAL_BODY_BUFFERED
          || result == IterationTag.EVAL_BODY_AGAIN)
    {
      // process the children recursively
      // children could be other JSP tags, plain view tags, or plain objects

      StringBuilder bodyBuilder = new StringBuilder();
      // haha - body builder

      for (Object child : getChildren()) {
        bodyBuilder.append(child.toString());
      }
      // EVAL_BODY_BUFFERED == EVAL_BODY_AGAIN == 2, so we also have to make sure that
      // we're dealing with a BodyTag
      if (result == BodyTag.EVAL_BODY_BUFFERED && bodyTag != null) {
        BodyContent bodyContent = new ViewJspWriter(bodyBuilder.toString());
        bodyTag.setBodyContent(bodyContent);
        bodyTag.doInitBody();
      }
      else {
        JspWriter out = pageContext.getOut();
        out.write(bodyBuilder.toString());
      }
      if (iterationTag != null) {
        int nextStep = iterationTag.doAfterBody();
        process(tag, nextStep);
      }
    }
  }

  protected void doEndTag(Tag tag) throws Exception {
    tag.doEndTag();
  }

  /**
   * Meant to be implemented by subclasses to validate required attributes. This implementation does
   * nothing.
   */
  protected void validate() throws RequiredTagAttributeException {
  }
}
